//  This software code is made available "AS IS" without warranties of any
//  kind.  You may copy, display, modify and redistribute the software
//  code either by itself or as incorporated into your code; provided that
//  you do not remove any proprietary notices.  Your use of this software
//  code is at your own risk and you waive any claim against Amazon
//  Digital Services, Inc. or its affiliates with respect to your use of
//  this software code. (c) 2006 Amazon Digital Services, Inc. or its
//  affiliates.

package com.amazon.s3;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpMethod;

/**
 * A Response object returned from AWSAuthConnection.get().  Exposes the attribute object, which
 * represents the retrieved object.
 */
public class GetResponse extends Response {
    public S3Object object;
    
    private InputStream is;
    /**
     * Pulls a representation of an S3Object out of the HttpURLConnection response.
     */
    public GetResponse(HttpMethod connection) throws IOException {
        super(connection);
        if (connection.getStatusCode() < 400) {
            Map metadata = extractMetadata(connection);
            //byte[] body = slurpInputStream(connection.getInputStream());
            //this.object = new S3Object(body, metadata);
            is = connection.getResponseBodyAsStream();
        }
    }
    
   
    
    

    /**
     * Examines the response's header fields and returns a Map from String to List of Strings
     * representing the object's metadata.
     */
    private Map extractMetadata(HttpMethod connection) {
        TreeMap metadata = new TreeMap();
        Header[] headers = connection.getResponseHeaders();
        for (Header header : headers) {
            String key = (String)header.getName();
            System.out.println("Key:"+key);
            if (key == null) continue;
            if (key.startsWith(Utils.METADATA_PREFIX)) {
                metadata.put(key.substring(Utils.METADATA_PREFIX.length()), header.getValue());
                System.out.println("Val:"+header.getValue());
            }
        }

        return metadata;
    }

    
    public InputStream getIs() {
    	return is;
    }
    
}
